<template>
    <div class="map-view">
        <div id="map" ref="mapRef"></div>
        <!-- 地图控件 -->
        <div class="map-controls">
            <el-button type="primary" @click="toggleOverlayHandler">
                {{ showOverlay ? '关闭点击弹窗' : '开启点击弹窗' }}
            </el-button>
            <el-button type="primary" @click="showPrint = !showPrint">
                打印地图
            </el-button>
            <el-button type="primary" @click="toggleDimension">
                {{ is3D ? '切换2D' : '切换3D' }}
            </el-button>
            <el-button type="primary" @click="showCoordinatePicker = !showCoordinatePicker">
                {{ showCoordinatePicker ? '关闭坐标拾取' : '坐标拾取' }}
            </el-button>
            <el-button type="primary" @click="handleToggleBuildings">
                {{ showBuildings ? '移除建筑物' : '叠加建筑物' }}
            </el-button>
        </div>
        <!-- 坐标拾取面板 -->
        <CoordinatePicker v-if="showCoordinatePicker" :map="map" @picked="handleCoordinatePicked"
            @close="showCoordinatePicker = false" />
        <el-dialog v-model="coordinateDialogVisible" title="拾取坐标" width="300px" :close-on-click-modal="false">
            <div v-if="pickedCoordinate">
                <div>经度：{{ pickedCoordinate[0] }}</div>
                <div>纬度：{{ pickedCoordinate[1] }}</div>
            </div>
            <template #footer>
                <el-button @click="coordinateDialogVisible = false">关闭</el-button>
            </template>
        </el-dialog>
        <!-- 打印面板 -->
        <div v-if="showPrint" class="print-container">
            <PrintMap :map="map" @close="showPrint = false" />
        </div>
        <!-- 底部控制区 -->
        <div class="bottom-controls">
            <!-- 底图切换 -->
            <div class="basemap-switch">
                <el-radio-group v-model="currentBaseMap" @change="handleBaseMapChange" size="small">
                    <el-radio-button value="vec">矢量</el-radio-button>
                    <el-radio-button value="img">影像</el-radio-button>
                    <el-radio-button value="ter">地形</el-radio-button>
                </el-radio-group>
            </div>
            <!-- 图层控制器 -->
            <div class="layer-control-wrapper">
                <el-button size="small" @click="layerControlOpen = !layerControlOpen" style="margin-bottom: 4px;">
                    <span v-if="layerControlOpen">收起图层</span>
                    <span v-else>展开图层</span>
                </el-button>
                <LayerControl v-if="map && layerControlOpen" :layers="layers" :map="map" />
            </div>
        </div>
        <!-- 工具区 -->
        <div v-if="map && showTool" class="tools-container" @click.stop>
            <div class="tools-group">
                <el-button size="small" @click="drawToolsOpen = !drawToolsOpen" style="margin-bottom: 4px;">
                    <span v-if="drawToolsOpen">收起工具</span>
                    <span v-else>展开工具</span>
                </el-button>
                <DrawTools v-if="drawToolsOpen" ref="drawToolsRef" @draw-type-change="handleDrawTypeChange"
                    @clear="handleClear" />
            </div>
        </div>
        <div id="popup" class="ol-popup">
            <a href="#" id="popup-closer" class="ol-popup-closer"></a>
            <div id="popup-content"></div>
        </div>
    </div>
</template>

<script setup>
import ScaleLine from 'ol/control/ScaleLine'
import createCesiumScaleLine from '../utils/CesiumScaleLine.js'
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import 'ol/ol.css'
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { TileGrid } from 'ol/tilegrid'
import XYZ from 'ol/source/XYZ'
import { Draw, Modify, Snap } from 'ol/interaction'
import { doubleClick } from 'ol/events/condition'
import { Style, Fill, Stroke, Circle } from 'ol/style'
import { get as getProjection } from 'ol/proj'
import LayerControl from './LayerControl.vue'
import DrawTools from './DrawTools.vue'
import OLCesium from 'olcs/OLCesium';
import Plot from 'ol-plot'
import 'cesium/Build/Cesium/Widgets/widgets.css'
import PrintMap from './PrintMap.vue'
import CoordinatePicker from './CoordinatePicker.vue'
import { createGeoJSONLayer } from '../utils/map-utils'
import OverlayHandler from '../utils/OverlayHandler'

const layerControlOpen = ref(true) // 图层控制器展开状态
const drawToolsOpen = ref(false) // 绘制工具展开状态
const mapRef = ref(null)
const is3D = ref(false)
const showTool = ref(false)
const layers = ref([])
const currentBaseMap = ref('vec')
// 当前底图图层组
const currentBaseLayers = ref([])
const map = ref(null)
let ol3d = null
let draw = null
let snap = null
let vectorSource = null
let vectorLayer = null
let baseMapLayers = {
    vec: null,
    cva: null,
    img: null,
    cia: null,
    ter: null,
    cta: null
}
let plotDraw = null;
let plot = null;
// 天地图 token
const TDT_TOKEN = '8068dc3bdd894e5bdc0bff5d1cd6368d'

// 添加打印控制状态
const showPrint = ref(false)
const showCoordinatePicker = ref(false)
const coordinateDialogVisible = ref(false)
const pickedCoordinate = ref(null)
const showBuildings = ref(false)
const showOverlay = ref(false) // 控制OverlayHandler开关
let buildingsLayer = null
let overlayHandler = null
let scaleLineControl = null

// Cesium三维比例尺控件
let cesiumScaleLine = null;

// 创建天地图图层
const createTiandituLayer = (layerType, title, visible = true) => {
    // 动态生成天地图瓦片url
    const urlTemplate = `https://t{0-7}.tianditu.gov.cn/${layerType}_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=${layerType}&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${TDT_TOKEN}`;
    const xyzSource = new XYZ({
        url: urlTemplate,
        projection: 'EPSG:4326',
        crossOrigin: 'anonymous',
        wrapX: true,
        transition: 0,
        tileGrid: new TileGrid({
            extent: [-180, -90, 180, 90],
            resolutions: Array.from({ length: 19 }, (_, i) => 360 / (Math.pow(2, i) * 256)),
            tileSize: [256, 256],
            minZoom: 0,
            maxZoom: 18,
            origin: [-180, 90]
        })
    });
    const layer = new TileLayer({
        source: xyzSource,
        title: title,
        visible: visible,
        preload: Infinity,
        zIndex: layerType.includes('c') ? 2 : 1,
        useInterimTilesOnError: true,
        wrapX: true
    });
    return layer;
}

// 获取指定类型的底图图层组
const getBaseMapLayers = (type) => {
    switch (type) {
        case 'vec':
            return [
                createTiandituLayer('vec', '矢量'),
                createTiandituLayer('cva', '矢量注记')
            ]
        case 'img':
            return [
                createTiandituLayer('img', '影像'),
                createTiandituLayer('cia', '影像注记')
            ]
        case 'ter':
            return [
                createTiandituLayer('ter', '地形'),
                createTiandituLayer('cta', '地形注记')
            ]
        default:
            return []
    }
}

// 初始化2D地图
const initMap = () => {
    // 初始化默认底图（矢量）
    currentBaseLayers.value = getBaseMapLayers('vec')

    // 设置图层列表
    layers.value = [...currentBaseLayers.value]
    map.value = new Map({
        target: mapRef.value,
        layers: layers.value,
        view: new View({
            projection: 'EPSG:4326',
            center: [104.5, 35.5],
            zoom: 4,
            maxZoom: 18,
            minZoom: 1,
            constrainResolution: true,
            multiWorld: true,
            enableRotation: false
        })
    })
    plot = new Plot(map.value);
    // 将plot的图层加入layers
    if (plot && plot.plotLayer) {
        map.value.addLayer(plot.plotLayer);
    }
    //同步底图到layers
    layers.value = map.value.getLayers().getArray().filter(layer => {
        return layer.get('title') && (layer.get('title').includes('矢量') || layer.get('title').includes('影像') || layer.get('title').includes('地形'));
    });
    // 同步所有图层到layers,当plot.plotUtils.getFeatures().length > 0时，显示plot的图层
    if (plot && plot.plotLayer && plot.plotUtils.getFeatures().length > 0) {
        layers.value.push(plot.plotLayer);
    }

    showTool.value = true;
    // 初始化OverlayHandler（默认关闭）
    if (overlayHandler) {
        overlayHandler = null;
    }
    if (showOverlay.value && map.value) {
        overlayHandler = new OverlayHandler(map.value, null, null);
    }

    // 添加比例尺控件
    if (scaleLineControl) {
        map.value.removeControl(scaleLineControl);
        scaleLineControl = null;
    }
    scaleLineControl = new ScaleLine({
        units: 'metric',
        bar: true,
        steps: 4,
        minWidth: 100
    });
    map.value.addControl(scaleLineControl);
}
// 切换OverlayHandler开关
const toggleOverlayHandler = () => {
    showOverlay.value = !showOverlay.value;
    if (showOverlay.value && map.value) {
        overlayHandler = new OverlayHandler(map.value, null, null);
    } else if (!showOverlay.value && overlayHandler) {
        // 移除所有overlay和事件
        if (overlayHandler.staticOverlay) {
            try {
                map.value.removeOverlay(overlayHandler.staticOverlay);
            } catch (e) { }
            // 彻底移除DOM
            const el = overlayHandler.staticOverlay.getElement();
            if (el && el.parentNode) {
                el.parentNode.removeChild(el);
            }
        }
        overlayHandler = null;
    }
}
// 切换底图
const handleBaseMapChange = (type) => {
    console.log('切换底图:', type, currentBaseMap.value)

    if (!map.value) return

    // 移除当前底图和标注图层
    const mapLayers = map.value.getLayers()
    const baseLayersToRemove = currentBaseLayers.value.filter((layer, index) => index < 2);
    baseLayersToRemove.forEach(layer => {
        if (layer) {
            map.value.removeLayer(layer)
        }
    });

    // 创建新的底图层
    const newBaseLayers = getBaseMapLayers(type)

    // 添加新底图到地图最底层，避免重复添加
    newBaseLayers.forEach((layer, index) => {
        if (layer && !mapLayers.getArray().includes(layer)) {
            mapLayers.insertAt(index, layer)
            // 确保图层已加载
            layer.getSource().refresh()
        }
    })

    // 更新当前底图信息
    currentBaseLayers.value = newBaseLayers
    layers.value = [...newBaseLayers]

    // 如果在3D模式下，需要刷新场景
    if (is3D.value && ol3d) {
        const scene = ol3d.getCesiumScene();
        if (scene) {
            // 移除所有图层
            scene.imageryLayers.removeAll();

            // 添加新的图层
            switch (type) {
                case 'vec':
                    addTiandituLayer(scene, 'vec');
                    addTiandituLayer(scene, 'cva', true);
                    break;
                case 'img':
                    addTiandituLayer(scene, 'img');
                    addTiandituLayer(scene, 'cia', true);
                    break;
                case 'ter':
                    addTiandituLayer(scene, 'ter');
                    addTiandituLayer(scene, 'cta', true);
                    break;
            }

            // 强制渲
            scene.requestRender();
        }
    }
}
// 监听底图类型变化
watch(currentBaseMap, (newType, oldType) => {
    if (newType !== oldType) {
        handleBaseMapChange(newType)
    }
})

// 清除所有工具状态
const clearAllTools = () => {
    // 停止标绘
    if (plot) {
        plot.plotEdit.deactivate()
        plot.plotDraw.deactivate()
    }
}

// 处理标绘工具变更
const handleDrawTypeChange = (drawType) => {
    // 如果选择了新工具
    if (drawType) {
        // 启动标绘
        if (plot) {
            // 先停止之前的绘制
            plot.plotEdit.deactivate()
            plot.plotDraw.deactivate()

            // 启动新的绘制
            plot.plotDraw.activate(drawType)
            plot.plotDraw.on('drawEnd', (f) => {
                console.log('绘制完成', f)
                layers.value = map.value.getLayers().getArray();
            });
        }
    } else {
        // 如果取消选择工具，停止标绘
        if (plot) {
            plot.plotEdit.deactivate()
            plot.plotDraw.deactivate()
        }
    }
    // 标绘后同步图层
    nextTick(() => {
        if (map.value) {
            layers.value = map.value.getLayers().getArray();
        }
    });
}
const drawToolsRef = ref(null);
// 清除所有绘制的图形
const handleClear = () => {
    // 清除所有要素
    if (plot) {
        plot.plotUtils.removeAllFeatures()
        // 停止标绘
        plot.plotEdit.deactivate()
        plot.plotDraw.deactivate()
        if (plot.plotLayer) {
            map.value.removeLayer(plot.plotLayer);
        }
        if (map.value) {
            layers.value = map.value.getLayers().getArray();
        }
    }
    // 重置工具状态
    if (drawToolsRef.value) {
        drawToolsRef.value.resetTool()
    }
    // 清除后同步图层
    nextTick(() => {
        if (map.value) {
            layers.value = map.value.getLayers().getArray();
        }
    });
}
// 添加天地图底图
const addTiandituLayer = (scene, type, isLabel = false) => {
    const layer = scene.imageryLayers.addImageryProvider(
        new Cesium.WebMapTileServiceImageryProvider({
            url: `https://t{s}.tianditu.gov.cn/${type}_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=${type}&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&tk=${TDT_TOKEN}`,
            layer: type,
            style: "default",
            format: "tiles",
            tileMatrixSetID: "c",
            subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
            tilingScheme: new Cesium.GeographicTilingScheme(),
            tileMatrixLabels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"],
            maximumLevel: 18,
            minimumLevel: 0,
            credit: new Cesium.Credit('天地图全球影像服务')
        })
    );

    // 调整图层渲染参数
    if (isLabel) {
        layer.alpha = 1.0;
        layer.brightness = 1.1;    // 提高亮度
        layer.contrast = 1.2;      // 提高对比度
        layer.gamma = 0.9;         // 调整伽马值以增强文字清晰度
        layer.saturation = 1.1;    // 略微提高饱和度
    } else {
        layer.alpha = 1.0;
        layer.brightness = 1.05;
        layer.contrast = 1.1;
        layer.gamma = 1.0;
    }

    return layer;
};
// 初始化3D视图
const init3D = () => {
    try {
        // 基本配置
        ol3d = new OLCesium({
            map: map.value,
            target: mapRef.value,
            enableTerrain: false,
            sceneOptions: {
                scene3DOnly: true,
                baseLayerPicker: false,
                globe: {
                    enableLighting: false,
                    baseColor: Cesium.Color.WHITE,
                    showGroundAtmosphere: true,
                    tileCacheSize: 2000,                    // 增加缓存小
                    maximumScreenSpaceError: 2,             // 调整以平衡性能和质量
                    maximumTileLevel: 20,
                    preloadSiblings: true,
                    preloadAncestors: true,
                    loadingDescendantLimit: 20,
                    preferredTileSize: 512,
                    // 添加性能优化配置
                    tileLoadProgressEvent: false,           // 禁用加载度事件
                    enableLighting: false,                  // 禁用光照
                    showWaterEffect: false,                 // 禁用水面效果
                    requestRenderMode: true,                // 按需渲染
                    maximumRenderTimeChange: Infinity       // 无限制渲染时间
                }
            }
        });

        Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(80, 22, 130, 55);

        // 获取场景
        const scene = ol3d.getCesiumScene();
        if (!scene) {
            console.error('3D场景初始化失败');
            return;
        }

        // 性能优化配置
        scene.globe.enableLighting = false;
        scene.globe.showGroundAtmosphere = true;
        scene.globe.backFaceCulling = true;               // 启用背面裁剪
        scene.globe.showSkirts = false;                   // 禁用裙边
        scene.globe.tileCacheSize = 2000;
        scene.globe.maximumScreenSpaceError = 2;

        // 禁用不必要的特性
        scene.fog.enabled = false;                        // 禁用雾效果
        scene.skyAtmosphere.show = false;                 // 禁用大气层
        scene.sun = undefined;                            // 禁用太阳
        scene.moon = undefined;                           // 禁用月
        scene.skyBox.show = false;                        // 禁用天空盒

        // 设置渲染模式
        scene.requestRenderMode = true;                   // 按需渲染
        scene.maximumRenderTimeChange = Infinity;         // 无限制渲染时

        // 优化内存使用
        scene.globe.tileLoadProgressEvent.removeAllListeners();
        scene.globe.tileLoadProgressEvent = undefined;

        // 修改相机设置以优化性能
        scene.camera.setView({
            destination: Cesium.Cartesian3.fromDegrees(104.5, 35.5, 80000),
            orientation: {
                heading: 0.0,
                pitch: -Math.PI / 3,
                roll: 0.0
            }
        });

        // 设置相机限制以优化性能
        scene.screenSpaceCameraController.minimumZoomDistance = 50000;      // 增加最小缩放距离
        scene.screenSpaceCameraController.maximumZoomDistance = 20000000;
        scene.screenSpaceCameraController.enableTilt = false;               // 禁用倾斜
        scene.screenSpaceCameraController.enableLook = false;               // 禁用环视

        // 优化图层加载
        const addTiandituLayerOptimized = (type, isLabel = false) => {
            const layer = scene.imageryLayers.addImageryProvider(
                new Cesium.WebMapTileServiceImageryProvider({
                    url: `https://t{s}.tianditu.gov.cn/${type}_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=${type}&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&tk=${TDT_TOKEN}`,
                    layer: type,
                    style: "default",
                    format: "tiles",
                    tileMatrixSetID: "c",
                    subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
                    tilingScheme: new Cesium.GeographicTilingScheme(),
                    tileMatrixLabels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"],
                    maximumLevel: 18,
                    minimumLevel: 0,
                    enablePickFeatures: false,            // 禁用拾取能
                    rectangle: Cesium.Rectangle.fromDegrees(70, 15, 140, 55) // 限制加载范围到中国区
                })
            );

            if (isLabel) {
                layer.alpha = 1.0;
                layer.brightness = 1.1;
                layer.contrast = 1.2;
                layer.gamma = 0.9;
                layer.saturation = 1.1;
            }

            return layer;
        };

        // 使用优后图层加载函数
        scene.imageryLayers.removeAll();
        switch (currentBaseMap.value) {
            case 'vec':
                addTiandituLayerOptimized('vec');
                addTiandituLayerOptimized('cva', true);
                break;
            case 'img':
                addTiandituLayerOptimized('img');
                addTiandituLayerOptimized('cia', true);
                break;
            case 'ter':
                addTiandituLayerOptimized('ter');
                addTiandituLayerOptimized('cta', true);
                break;
        }

        // 强制渲染一次
        scene.requestRender();

        // 创建Cesium三维比例尺控件
        if (cesiumScaleLine) {
            cesiumScaleLine.destroy();
            cesiumScaleLine = null;
        }
        cesiumScaleLine = createCesiumScaleLine(scene, mapRef.value);
        // 2D比例尺控件隐藏
        if (scaleLineControl && map.value) {
            map.value.removeControl(scaleLineControl);
        }

    } catch (error) {
        console.error('初始化3D视图失败');
    }
}

// 切换2D/3D
const toggleDimension = () => {
    try {
        if (!ol3d) {
            init3D();
        }

        if (!ol3d) {
            console.error('3D始化失败');
            return;
        }

        is3D.value = !is3D.value;
        ol3d.setEnabled(is3D.value);

        // 保证比例尺控件在三维切换时始终存在
        if (is3D.value) {
            // 隐藏2D比例尺，显示3D比例尺
            if (scaleLineControl && map.value) {
                map.value.removeControl(scaleLineControl);
            }
            const scene = ol3d.getCesiumScene();
            if (scene) {
                if (cesiumScaleLine) {
                    cesiumScaleLine.destroy();
                    cesiumScaleLine = null;
                }
                cesiumScaleLine = createCesiumScaleLine(scene, mapRef.value);
                scene.shadowMap.enabled = true;
                // 刷新底图
                nextTick(() => {
                    handleBaseMapChange(currentBaseMap.value);
                });
                setTimeout(() => {
                    console.log('切换到3D模式:', ol3d.getDataSourceDisplay());
                }, 10000); // 确保渲染完成
                if (overlayHandler) {
                    overlayHandler.ol3d = ol3d;
                    overlayHandler.scene = scene;
                }
            }
        } else {
            // 2D时显示2D比例尺，隐藏3D比例尺
            if (cesiumScaleLine) {
                cesiumScaleLine.destroy();
                cesiumScaleLine = null;
            }
            if (scaleLineControl && map.value && !map.value.getControls().getArray().includes(scaleLineControl)) {
                map.value.addControl(scaleLineControl);
            }
        }
    } catch (error) {
        console.error('切换3D模式失败:', error);
    }
}

// 监听窗口大小变化
const handleResize = () => {
    if (map.value) {
        map.value.updateSize()
    }
}
// 初始化地图大小监听
const initResizeListener = () => {
    window.addEventListener('resize', handleResize)

    // 创建 ResizeObserver 监听容器大小变化
    const resizeObserver = new ResizeObserver(() => {
        nextTick(() => {
            handleResize()
        })
    })

    // 监听地图容器
    if (mapRef.value) {
        resizeObserver.observe(mapRef.value)
    }
}
// 在组件卸载时清理

onMounted(() => {
    initMap()
    initResizeListener()
})

onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    // resizeObserver.disconnect()
    if (plot) {
        plot.plotEdit.deactivate()
        plot.plotDraw.deactivate()
        plot = null
    }
    if (map.value) {
        map.value.setTarget(null)
    }
    if (ol3d) {
        ol3d.setEnabled(false)
        const scene = ol3d.getCesiumScene()
        if (scene) {
            scene.destroy()
        }
        ol3d = null
    }
    if (scaleLineControl && map.value) {
        map.value.removeControl(scaleLineControl);
        scaleLineControl = null;
    }
    if (cesiumScaleLine) {
        cesiumScaleLine.destroy();
        cesiumScaleLine = null;
    }
    if (overlayHandler && overlayHandler.staticOverlay) {
        map.value.removeOverlay(overlayHandler.staticOverlay);
    }
    overlayHandler = null;
})

function handleCoordinatePicked(coord) {
    pickedCoordinate.value = coord
    coordinateDialogVisible.value = true
    showCoordinatePicker.value = false
}

async function handleToggleBuildings() {
    if (!map.value) return
    if (!showBuildings.value) {
        // 添加建筑物图层
        buildingsLayer = await createGeoJSONLayer({
            data: 'https://openlayers.org/ol-cesium/examples/data/geojson/buildings.geojson',
            title: '建筑物',
            style: {
                fillColor: 'rgba(0,0,0,0)', // 只描边不填充
                strokeColor: '#666',
                strokeWidth: 1
            },
            opacity: 1,
            visible: map.value.getView().getZoom() >= 15, // 初始根据缩放级别决定可见性
            zIndex: 20
        })
        buildingsLayer.set('olcs_shadows', true);
        map.value.addLayer(buildingsLayer)
        // 更新图层控制
        layers.value = map.value.getLayers().getArray()
        showBuildings.value = true
        //自动缩放到建筑物范围
        const extent = buildingsLayer.getSource().getExtent()
        map.value.getView().fit(extent, {
            duration: 1000,
            maxZoom: 18,
            size: map.value.getSize()
        })
        // 监听缩放级别，动态显示/隐藏建筑物图层，并强制限制最大缩放级别
        map.value.getView().on('change:resolution', () => {
            const zoom = map.value.getView().getZoom();
            // 限制最大缩放级别，防止高等级频繁请求
            if (zoom > 18) {
                map.value.getView().setZoom(18);
                return;
            }
            if (buildingsLayer) {
                buildingsLayer.setVisible(zoom >= 15)
            }
        })
    } else {
        // 移除建筑物图层
        if (buildingsLayer) {
            // 彻底移除所有名为“建筑物”的图层，防止多实例残留
            map.value.getLayers().getArray().forEach(layer => {
                if (layer.get && layer.get('title') === '建筑物') {
                    map.value.removeLayer(layer)
                }
            })
            nextTick(() => {
                layers.value = map.value.getLayers().getArray()
            })
            buildingsLayer = null
        }
        showBuildings.value = false
        // 重置视图到初始位置
        map.value.getView().setCenter([104.5, 35.5])
        map.value.getView().setZoom(4)
    }
}
</script>

<style lang="scss" scoped>
.map-view {
    width: 100%;
    height: 100%;
    position: relative;
}

#map {
    width: 100%;
    height: 100%;
}

.map-controls {
    position: absolute;
    top: vw(20);
    right: vw(20);
    z-index: 1000;
}

.bottom-controls {
    position: absolute;
    bottom: vw(20);
    right: vw(20);
    z-index: 1000;
    display: flex;
    gap: vw(10);
    align-items: flex-end;
}

.basemap-switch {
    background-color: rgba(255, 255, 255, 0.8);
    padding: vw(1) vw(5) vw(5) vw(5);
    border-radius: vw(4);
    box-shadow: 0 vw(2) vw(12) 0 rgba(0, 0, 0, 0.1);
}

/* 按钮样式 */
:deep(.el-button),
:deep(.el-radio-button__inner) {
    padding: vw(8) vw(15);
    font-size: vw(14);
    height: vw(32);
    line-height: 1;
}

/* 地图控件样式 */
:deep(.ol-control) {
    position: absolute;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: vw(4);
    padding: vw(2);
}

:deep(.ol-control button) {
    display: block;
    margin: vw(1);
    padding: 0;
    color: #666;
    font-size: vw(16);
    font-weight: bold;
    text-decoration: none;
    text-align: center;
    height: vw(22);
    width: vw(22);
    line-height: vw(22);
    background-color: rgba(255, 255, 255, 0.8);
    border: none;
    border-radius: vw(2);
}

/* 样式 */
:deep(.el-icon) {
    font-size: vw(16);
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
    .basemap-switch {
        background-color: rgba(0, 0, 0, 0.8);
    }

    :deep(.el-radio-button__inner) {
        background-color: rgba(0, 0, 0, 0.8);
        color: #fff;
        border-color: #666;
    }
}

.tools-container {
    position: absolute;
    top: vw(70);
    right: vw(20);
    z-index: 1000;
    display: flex;
    flex-direction: column;
    gap: vw(10);

    .tools-group {
        background-color: rgba(255, 255, 255, 0.8);
        border-radius: vw(4);
        box-shadow: 0 vw(2) vw(12) 0 rgba(0, 0, 0, 0.1);
    }
}

.print-container {
    position: absolute;
    top: vw(80);
    left: vw(200);
    z-index: 1000;
    max-width: vw(1000);
    width: vw(1000);
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: vw(4);
    box-shadow: 0 vw(2) vw(12) 0 rgba(0, 0, 0, 0.1);
}

.layer-control-wrapper {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
}

.ol-popup {
    filter: drop-shadow(0 1px 4px #0003);
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 10px;
    min-width: 280px;
    padding: 15px;
    position: absolute;
    // bottom: -12px;
    left: -50px
}

.ol-popup:after,
.ol-popup:before {
    content: " ";
    pointer-events: none;
    border: solid #0000;
    width: 0;
    height: 0;
    position: absolute;
    top: 100%
}

.ol-popup:after {
    border-width: 10px;
    border-top-color: #fff;
    margin-left: -10px;
    left: 48px
}

.ol-popup:before {
    border-width: 11px;
    border-top-color: #ccc;
    margin-left: -11px;
    left: 48px
}

.ol-popup-closer {
    text-decoration: none;
    position: absolute;
    top: 2px;
    right: 8px
}

.ol-popup-closer:after {
    content: "✖"
}

.popover-content {
    min-width: 180px
}
</style>